﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Configuration;
using System.IO;

namespace LOGISTCBUS.WebUI
{
    public class AjaxFileUpload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files != null && context.Request.Files.Count > 0)
            {
                var file = context.Request.Files[0];
                var urlFiles = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["urlFiles"])
                        ? ConfigurationManager.AppSettings["urlFiles"].ToString()
                        : String.Empty;
                String serverUrl = HttpContext.Current.Server.MapPath(urlFiles);
                String fileName = file.FileName;
                String targetFilePath = GetFileName(Path.Combine(serverUrl, fileName));

                if (!Directory.Exists(serverUrl))
                    Directory.CreateDirectory(serverUrl);

                if (!String.IsNullOrEmpty(fileName))
                    file.SaveAs(targetFilePath);

                var obj = new
                {
                    Name = System.IO.Path.GetFileName(targetFilePath)
                };

                JavaScriptSerializer oSerializer = new JavaScriptSerializer();
                string jsonResult = oSerializer.Serialize(obj);
                context.Response.ContentType = "text/html";
                context.Response.Write(jsonResult);
            }
        }

        String GetFileName(String savedFileName)
        {
            var contador = 1;
            while (System.IO.File.Exists(savedFileName))
            {
                var extension = System.IO.Path.GetExtension(savedFileName);
                savedFileName = savedFileName.Remove(savedFileName.LastIndexOf('.'));
                if (Path.GetFileName(savedFileName).Contains('_'))
                {
                    savedFileName = savedFileName.Remove(savedFileName.LastIndexOf('_'));
                    savedFileName = String.Format(savedFileName + "_{0}" + extension, contador);
                }
                else
                    savedFileName = String.Format(savedFileName + "_{0}" + extension, contador);
                contador++;
            }
            return savedFileName;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}